<template>
  <div class="login">
    <el-form ref="form"
             class="login-from"
             :model="form"
             :rules="rules"
             label-position="top"
             label-width="80px">
      <el-form-item label="手机号"
                    prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码"
                    prop="password">
        <el-input v-model="form.password"
                  type='password'></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   class="login-btn"
                   :loading="isLoginLoading"
                   @click="onSubmit">登录</el-button>
        <el-button class="login-btn">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { login } from '@/services/logIn'
import { Form } from 'element-ui'
export default Vue.extend({
  name: 'LoginIndex',
  data() {
    return {
      form: {
        phone: '15510792995',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '请输入6-18位的密码', trigger: 'blur' }
        ]
      },
      isLoginLoading: false
    }
  },
  methods: {
    async onSubmit() {
      try {
        await (this.$refs.form as Form).validate()
        this.isLoginLoading = true
        const { data } = await login(this.form)
        if (data.state !== 1 && data.state !== 200) {
          this.$message({
            message: data.message,
            type: 'error'
          })
        } else {
          this.$store.commit('setUser', data.content)
          this.$message({
            message: '登录成功',
            type: 'success'
          })
          this.$router.push((this.$route.query.redirect as string) || '/')
        }
      } catch (error) {
        console.log('登录失败:' + error)
      }
      this.isLoginLoading = false
    }
  }
})
</script>
<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-from {
    background: #ffffff;
    padding: 20px;
    border-radius: 5px;
    min-width: 300px;
  }
  .login-btn {
    width: 100%;
    margin: 0 0 10px 0;
  }
}
</style>
